# coding=utf-8

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.utils import timezone


class UserManager(BaseUserManager):
    def create_user(self, username, password=None, **extra_fields):
        if not username:
            raise ValueError(u'请输入用户名')
        user = self.model(username=username, is_superuser=False,
                          last_login=timezone.now(), **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, **extra_fields):
        user = self.create_user(username, password, **extra_fields)
        user.is_active = True
        user.is_superuser = True
        user.save(using=self._db)
        return user


class User(AbstractBaseUser, PermissionsMixin):
    FEMALE = 1
    MALE = 2
    GENDER_CHOICES = (
        (FEMALE, u'女'),
        (MALE, u'男'),
    )
    username = models.CharField(verbose_name=u'帐号', max_length=30, unique=True, db_index=True)
    nickname = models.CharField(verbose_name=u'姓名', max_length=30, null=True, blank=True)
    head_img = models.CharField(verbose_name='头像', max_length=200, null=True)
    gender = models.PositiveSmallIntegerField(choices=GENDER_CHOICES, verbose_name=u"性别", default=MALE)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    class Meta:
        db_table = "auth_user"
        verbose_name = u"账号"
        ordering = ['-id']
